<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
      :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :scroll-x="1090">
      <template #toolbar>
          <h1 class="flex items-center">
            <span>总价：<span class="text-red-600 font-bold text-xl">{{ allTotal }}</span></span>
            <span class="mx-6"></span>
            <span>总磅费：<span class="text-red-600 font-bold text-xl">{{ allWeightFee }}</span></span>
          </h1>
          <!-- <n-button type="primary" @click="reloadTable">刷新数据</n-button> -->
        </template>
    </BasicTable>

    <n-modal  :show-icon="false" preset="dialog"  style="width: 1000px">
      <OrderDetail  />
      <OrderItem  />
      <!-- <OrderShipment v-if="checkedOrder.orderStatus == OrderStatusEnum.PAID_OFF" :orderId="checkedOrder.id"
        :order="checkedOrder" @update:shipment="handleShipment" /> -->
      <template #action>
        <n-space>
          <n-button >关闭</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
import {  ref, onMounted } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getSettlementPage } from '@/api/weight/settlement';
import { getWeightNumber } from '@/api/weight/goodsType';
import { columns } from './columns';

const schemas = ref<FormSchema[]>([
  {
    field: 'time',
    component: 'NDatePicker',
    label: '结算时间',
    componentProps: {
      type: 'daterange',
      format: 'yyyy-MM-dd', // 显示格式为仅日期
      valueFormat: 'yyyy-MM-dd', // 值格式为仅日期
    },
    rules: [{ required: false }],
    //defaultValue: getTodayRange(), // 默认值设置为当天的日期范围
  },
  {
    field: 'employmentName',
    component: 'NInput',
    label: '操作员名称',
    rules: [{ required: false }],
  },
  {
    field: 'weightNumber',
    component: 'NSelect',
    label: '地磅编号',
    componentProps: {
      options: [], // 初始为空
      placeholder: '请选择地磅',
      filterable: true,
    },
    rules: [{ required: false, message: '请选择地磅编号', trigger: 'change' }],
  },
])



const message = useMessage();
// 确保actionRef正确初始化，设置为BasicTable实例的类型
const actionRef = ref<InstanceType<typeof BasicTable>>();
const allTotal = ref(0); // 总价响应式变量
const allWeightFee = ref(0); // 总磅费响应式变量

// 初始化params为响应式对象，用于存储表单查询参数
const params = ref<Recordable>({});

// 获取今天的日期范围（仅日期部分，不包含时间）
const getTodayRange = () => {
  const today = new Date();
  // 设置开始日期为今天（不包含具体时间）
  const startDate = new Date(today);
  startDate.setHours(0, 0, 0, 0);
  
  // 设置结束日期为今天（不包含具体时间）
  const endDate = new Date(today);
  endDate.setHours(0, 0, 0, 0);
  
  return [startDate, endDate];
};

const [register, { setProps, setFieldsValue }] = useForm({
  layout: 'inline', // 设置为inline布局，使按钮右对齐
  gridProps: { cols: '1 s:1 m:2 l:2 xl:5 2xl:4' },
  labelWidth: 100,
  schemas,
  showAdvancedButton: false, // 隐藏展开/收起按钮
});

// 处理时间范围参数并整合所有查询条件
const loadDataTable = async (res) => {
  try {
    // 深拷贝参数，避免直接修改原数据
    const requestParams = { ...params.value, ...res };
    
    // 特殊处理日期范围参数
    if (requestParams.time && Array.isArray(requestParams.time) && requestParams.time.length === 2) {
      // 提取开始日期和结束日期
      const [startDate, endDate] = requestParams.time;
      
      // 确保只使用日期部分
      if (startDate && endDate) {
        // 转换为日期对象确保只包含日期部分
        const startDateObj = new Date(startDate);
        const originalStartHours = startDateObj.getHours();
        startDateObj.setHours(0, 0, 0, 0);
        
        const endDateObj = new Date(endDate);
        const originalEndHours = endDateObj.getHours();
        endDateObj.setHours(0, 0, 0, 0);
        // 转换为时间戳格式
        requestParams.startTime = startDateObj.getTime();
        requestParams.endTime = endDateObj.getTime();
      } else {
        console.log('[loadDataTable] 日期范围不完整，跳过设置时间参数');
      }
      
      // 移除原始的time字段
      delete requestParams.time;
    } else {
      console.log('[loadDataTable] 没有检测到有效的日期范围参数:', requestParams.time);
    }
    console.log('[loadDataTable] API请求参数结果:', requestParams);
    // 调用API接口并返回结果
    const result = await getSettlementPage(requestParams);
    console.log('[loadDataTable] API返回结果:', result);
    
    // 从API返回结果中提取总价和总磅费
    if (result) {
      allTotal.value = result.allTotal || 0;
      allWeightFee.value = result.allWeightFee || 0;
    }
    
    return result;
  } catch (error) {
    console.error('[loadDataTable] 加载列表数据异常:', error);
    message.error('加载数据失败，请稍后重试');
    return { list: [], total: 0 }; // 返回空数据避免表格显示错误
  }
};

function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}



// 提交表单查询
function handleSubmit(values: Recordable) {
  // 存储表单值用于后续查询
  params.value = { ...values }; // 深拷贝避免引用问题
  // 重新加载表格数据
  reloadTable();
}

function reloadTable() {
  if (actionRef.value) {
    actionRef.value.reload();
  } else {
    console.error('actionRef未正确初始化');
  }
}

function handleReset(values: Recordable) {
  console.log(values);
}


// 组件挂载后加载数据
onMounted(async () => {
  try {
    // 同时请求两种数据
    const [ weightNumberArray] = await Promise.all([ getWeightNumber()]);
    
    // 创建新的schemas数组以确保响应式更新
    const newSchemas = [...schemas.value];
    
    // 处理地磅编号数据
    if (Array.isArray(weightNumberArray) && weightNumberArray.length > 0) {
      const weightNumberOptions = weightNumberArray.map(item => ({
        label: item.number,
        value: item.id,
      }));
      
      const weightNumberIndex = newSchemas.findIndex(s => s.field === 'weightNumber');
      if (weightNumberIndex !== -1) {
        newSchemas[weightNumberIndex] = {
          ...newSchemas[weightNumberIndex],
          componentProps: {
            ...newSchemas[weightNumberIndex].componentProps,
            options: weightNumberOptions
          }
        };
      }
    } else {
      message.warning('暂无地磅类型数据');
    }
    
    // 一次性更新整个表单配置
    setProps({ schemas: newSchemas });
    
    // 设置默认的时间范围值为当天
    setTimeout(() => {
      setFieldsValue({
        time: getTodayRange()
      });
      // 初始化时自动加载数据
      reloadTable();
    }, 100);
  } catch (error) {
    console.error('加载下拉框数据异常:', error);
    message.error('加载下拉框数据失败，请稍后重试');
  }
});


</script>

<style lang="less" scoped>
.n-form {
  :deep(.n-grid){
    display: flex !important;
    & > div{
      width: 240px;
    }
    & > div:nth-child(1){
      width: 360px;
    }
    & > div:nth-child(4){
      width: 720px;
    }
  }
}
</style>
